<template>
  <el-dialog v-model="dialogVisible" title="重置密码" :destroy-on-close="true" width="400px" draggable>
    <el-form ref="ruleFormRef" label-position="top" :model="form" :rules="rules">
      <el-form-item :label="`请输入&quot;${parameter.rowData.username}&quot;的新密码`" prop="newPassword">
        <el-input v-model="form.newPassword" placeholder="密码由8-20位大小写字母和数字组成" />
      </el-form-item>
    </el-form>
    <div class="foot">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts" name="ResetPassword">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";

let form = ref({
  newPassword: "",
});

const rules = reactive<any>({
  newPassword: [
    { required: true, message: "请输入密码" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{8,20}$/,
      message: "密码由8-20位大小写字母和数字组成",
      trigger: ["blur", "change"],
    },
  ],
});

export interface ResetParameterProps {
  rowData: any;
  resetApi?: (params: any) => void;
  getTableList?: () => void; // 获取表格数据的Api
}

// dialog状态
const dialogVisible = ref(false);
// 父组件传过来的参数
const parameter = ref<ResetParameterProps>({
  rowData: {},
});

// 接收父组件参数
const acceptParams = (params: ResetParameterProps) => {
  parameter.value = { ...parameter.value, ...params };
  dialogVisible.value = true;
};

// 重置密码
const ruleFormRef = ref<FormInstance>();
const handleSubmit = async () => {
  ruleFormRef.value.validate(async valid => {
    if (!valid) return;
    let params = {
      id: parameter.value.rowData.id,
      password: form.value.newPassword,
    };
    await parameter.value.resetApi(params);
    ElMessage.success({ message: `重置密码成功！` });
    parameter.value.getTableList && parameter.value.getTableList();
    dialogVisible.value = false;
  });
};

const handleCancel = () => {
  dialogVisible.value = false;
  form.value.newPassword = "";
};

defineExpose({
  acceptParams,
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
